package org.example.ag_notes.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.example.ag_notes.dto.auth.*;
import org.example.ag_notes.dto.response.Response;
import org.example.ag_notes.exception.AuthenticationException;
import org.example.ag_notes.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.example.ag_notes.dto.response.*;


//TODO规范返回体字段信息

@Tag(name = "用户认证" , description = "用户登录，注册，验证等")
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private AuthService authService;

    /**
     * 用户登录
     * @param request 登录请求
     * @return 包含令牌的响应
     */
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest request) {
        try {
            return ResponseEntity.ok(authService.login(request));
        } catch (AuthenticationException e) {
            return ResponseEntity
                    .status(HttpStatus.UNAUTHORIZED)
                    .body(ErrorResponse.of(HttpStatus.UNAUTHORIZED, "用户名或密码错误", "/api/auth/login"));
        }
    }

    /**
     * 用户注册
     * @param request 注册请求
     * @return 注册结果
     */
    @PostMapping("/register")
    public ResponseEntity<?> register(@Valid @RequestBody RegisterRequest request) {
        try {
            // 注册成功返回201 Created
            return ResponseEntity
                    .status(HttpStatus.CREATED)
                    .body(authService.register(request));

        } catch (DuplicateKeyException e) {
            // 用户名已经存在
            return ResponseEntity
                    .status(HttpStatus.CONFLICT)
                    .body(ErrorResponse.of(
                            HttpStatus.CONFLICT,
                            "用户名已经被注册",
                            "/api/auth/register"
                    ));
        }
    }
    /**
     * 账号注销
     * @param request 注销请求(包含刷新令牌)
     * @return 注销结果
     */
    @PostMapping("/logout")
    public ResponseEntity<?> logout(@RequestBody @Valid LogoutRequest request) {
        try {
            String refreshToken = request.getRefreshToken();

            // 2. 执行注销逻辑
            authService.logout(refreshToken, refreshToken);

            return ResponseEntity.noContent().build();

        } catch (AuthenticationException e) {
            return ResponseEntity
                    .status(HttpStatus.UNAUTHORIZED)
                    .body(Response.error(401, "错误"));
        }

    }

    /**
     * 刷新访问令牌
     * @param refreshToken 刷新令牌(从Authorization头获取)
     * @return 新的访问令牌
     */
    @PostMapping("/refresh")
    public ResponseEntity<Response<AuthResponse>> refreshToken(
            @RequestHeader("Authorization") String refreshToken) {
        AuthResponse response = authService.refreshToken(refreshToken);
        return ResponseEntity.ok(Response.success("令牌刷新成功", response));
    }

    /**
     * Token有效性验证
     * @param accessToken 访问令牌(从Authorization头获取)
     * @return 验证结果
     */
    @Operation(summary = "验证Token有效性")
    @PostMapping("/validate")
    public ResponseEntity<Response<Boolean>> validateToken(
            @RequestHeader("Authorization") String accessToken) {
        try {
            Response<Boolean> result = authService.validateToken(accessToken);
            return ResponseEntity.ok(result);

        } catch (AuthenticationException e) {
            return ResponseEntity
                    .status(HttpStatus.UNAUTHORIZED)
                    .body(Response.error(
                            HttpStatus.UNAUTHORIZED.value(),
                            "Token验证失败: " + e.getMessage()
                    ));
        }
    }

}